run
一次 go test -fuzz=Fuzz
UTF-8
錯誤不一樣\xfb
,轉之後便成了虛缺號 reverse_test.go:17: Before: "\xfb", after: "�"
wiki
上的 UTF-8
對照表\xfb
不在 UTF-8 的轉譯範圍內,所以會變成虛缺號debugger
來清楚看到變數變化過程Go
最常用的debugger 是 Delve
,那我自己是用 VSCode
所以我來教一下怎麼安裝Crtl + Shift + P
就可叫出快速指令, 那在上面輸入 Run and Debug,並點到圖中這個Install
就完成了想了解更多可以去這裡
utf8.VaildString
去檢測有沒有不合法的 Byte
Rerverse
改一下
func Reverse(s string) (string, error) { // 回傳值要加上 error
if !utf8.ValidString(s) { // 透過 utf8.VaildString 我們可以檢測不合法的 Byte
return s, errors.New("input is an invalid UTF-8 byte")
}
b := []rune(s)
for i, j := 0, len(b)-1; i < len(b)/2; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
return string(b), nil // 回傳記得也要加 nil
}
Reverse
改完了,我們的 Main
跟 Import
也要做一下適當的更改,不然參數對不上import (
"errors"
"fmt"
"unicode/utf8"
)
-----------------------------------------------------------------------
func main() {
input := "iron man write quick in thirty days"
rev, reverseError := Reverse(input) // 增加error參數去接
doubleRev, doubleReverError := Reverse(rev)
fmt.Printf("origin: %q\n", input)
fmt.Printf("reversed: %q\n, err: %v\n", rev, reverseError) // 把 error 印出來
fmt.Printf("after reversed twice: %q\n, err: %v\n", doubleRev, doubleReverError)
}
Fuzzing Test
的部分,我們要讓他有錯誤的時候就 return
// 原本的
rev:= Reverse(orig)
doubleRev:= Reverse(rev)
---------------------------------
// 後來的
rev, err1 := Reverse(orig)
if err1 != nil {
return
}
doubleRev, err2 := Reverse(rev)
if err2 != nil {
return
}
-fuzztime
的參數,不然除非他遇到錯誤他都不會停go test -fuzz=Fuzz -fuzztime 1200s
fuzz: elapsed: 0s, gathering baseline coverage: 0/17 completed
fuzz: elapsed: 0s, gathering baseline coverage: 17/17 completed, now fuzzing with 16 workers
fuzz: elapsed: 3s, execs: 698615 (232537/sec), new interesting: 24 (total: 41)
fuzz: elapsed: 6s, execs: 2236680 (513271/sec), new interesting: 25 (total: 42)
fuzz: elapsed: 9s, execs: 3585765 (448219/sec), new interesting: 25 (total: 42)
....................................................................................
fuzz: elapsed: 18m33s, execs: 483007441 (450800/sec), new interesting: 31 (total: 48)
fuzz: elapsed: 18m36s, execs: 484354532 (448469/sec), new interesting: 31 (total: 48)
fuzz: elapsed: 18m39s, execs: 485701835 (448003/sec), new interesting: 31 (total: 48)
fuzz: elapsed: 18m42s, execs: 487038983 (447214/sec), new interesting: 31 (total: 48)
fuzz: elapsed: 18m44s, execs: 487860986 (430396/sec), new interesting: 31 (total: 48)
PASS
ok go/fuzz 1124.723s